import axios from 'axios'
import { useMutation, useQueryClient } from 'react-query'

async function modifyTodo ({ id, isCompleted }) {
  return axios.patch(`/todos/${id}`, { isCompleted })
}

function ModifyTodoCompleted ({ todo }) {
  const queryClient = useQueryClient()
  const { mutate } = useMutation(modifyTodo, {
    onSuccess (response) {
      queryClient.setQueryData('todos', data =>
        data.map(todo => (todo.id === response.id ? response : todo))
      )
    }
  })
  return (
    <input
      onChange={event =>
        mutate({ id: todo.id, isCompleted: event.target.checked })
      }
      checked={todo.isCompleted}
      className='toggle'
      type='checkbox'
    />
  )
}

export default ModifyTodoCompleted
